//
//  BalanceViewController.m
//  danpin
//
//  Created by chuangjia on 4/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "BalanceViewController.h"
#import "orderconfig.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
@interface BalanceViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,strong) UIView *headerView;
@property(nonatomic,strong) UIImageView *iconView;
@property(nonatomic,strong) UILabel *levelLabel;
@property(nonatomic,strong) UIButton *tixianBtn;
@property(nonatomic,strong) NSMutableDictionary *userinfo;
@end

@implementation BalanceViewController
@synthesize tbView=_tbView;
@synthesize sectionArray=_sectionArray;
@synthesize currentPage=_currentPage;
@synthesize headerView=_headerView;
@synthesize iconView=_iconView;
@synthesize levelLabel=_levelLabel;
@synthesize tixianBtn=_tixianBtn;
@synthesize userinfo=_userinfo;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"余额";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    if (!_userinfo) {
        _userinfo = [[NSMutableDictionary alloc] init];
    }
    _userinfo = (NSMutableDictionary*)[ZShare sharedInstance].userInfo;
    self.isLoadFinished =NO;
    self.isRequesting = NO;
    self.currentPage = 0;
    [self initUI];
  
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.isLoadFinished =NO;
    self.isRequesting = NO;
    self.currentPage = 0;
    [self getShopBalanceList];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.tbView = nil;
}

-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    //
    _tbView.tableHeaderView =self.headerView;
    // setup infinite scrolling
    __weak typeof (self) wSelf = self;
    self.currentPage = 0;
    [_tbView addPullToRefreshWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        wSelf.isRefresh = NO;
        wSelf.currentPage = 0;
        wSelf.isLoadFinished = NO;
        [wSelf.tbView.pullToRefreshView startAnimating];
        [wSelf getShopBalanceList];
    }];
    //
    //
    [_tbView.pullToRefreshView setOYStyle];
    //
    // setup infinite scrolling
    [self.tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        wSelf.isRefresh = NO;
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.tbView.infiniteScrollingView stopAnimating];
            [wSelf.tbView setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        wSelf.currentPage =(int) [wSelf.sectionArray count];
        [wSelf  getShopBalanceList];
        
    }];
}
//==========
-(UIView*)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 120)];
        _headerView.backgroundColor =[UIColor whiteColor];
        UIImageView *backvv = [[UIImageView alloc] initWithFrame:_headerView.frame];
        backvv.image =[UIImage imageNamed:@"my_background.png"];
        [_headerView addSubview:backvv];
        backvv=nil;
        //
        _levelLabel =[[UILabel alloc] initWithFrame:CGRectZero];
        _levelLabel.frame = CGRectMake(0,PHOTO_FRAME_WIDTH*3, DEVICE_WIDTH, PHOTO_FRAME_WIDTH*2);
        _levelLabel.backgroundColor = [UIColor clearColor];
        _levelLabel.textColor =  [UIColor blackColor];
        _levelLabel.textAlignment = NSTextAlignmentCenter;
        _levelLabel.font = [UIFont boldSystemFontOfSize:13];
        [_headerView addSubview:_levelLabel];
        //
        _tixianBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        _tixianBtn.backgroundColor =UIColorFromRGB(0xFF7900);
        _tixianBtn.tag=1;
        _tixianBtn.frame=CGRectMake((DEVICE_WIDTH-widthAuto(50))/2, _levelLabel.frame.origin.y+_levelLabel.frame.size.height +PHOTO_FRAME_WIDTH, widthAuto(50), hightAuto(30));
        _tixianBtn.titleLabel.font =FONT(13);
        [_tixianBtn setTitle:@"提现" forState:UIControlStateNormal];
        _tixianBtn.layer.cornerRadius = _tixianBtn.frame.size.height/2;
        _tixianBtn.layer.masksToBounds = YES;
        [_tixianBtn addTarget:self action:@selector(TixianClick) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:_tixianBtn];
        
    }
    NSString *middleFace =[[NSString stringWithFormat:@"%@",[_userinfo objectForKey:@"largeFace"]] replaceNullString];
    if (middleFace.length>0) {
        [_iconView sd_setImageWithURL:[NSURL URLWithString:middleFace] placeholderImage:[UIImage imageNamed:@"user_face.png"]];
    }
    NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfo objectForKey:@"user_balance"]] replaceNullString];
    if (user_balance.length>0) {
        float v = [user_balance floatValue];
        if (v>0) {
            _tixianBtn.enabled = YES;
            _tixianBtn.backgroundColor =UIColorFromRGB(0xFF7900);
        }else{
            _tixianBtn.enabled = NO;
            _tixianBtn.backgroundColor =UIColorFromRGB(0xcccccc);
        }
        _levelLabel.text =[NSString stringWithFormat:@"余额:%@",user_balance];
    }else{
        _levelLabel.text =[NSString stringWithFormat:@"余额:%@",@"0.00"];
        _tixianBtn.enabled = NO;
        _tixianBtn.backgroundColor =UIColorFromRGB(0xcccccc);
    }

    return _headerView;
}

-(void)TixianClick
{
    BalanceCashViewController *cash = [[BalanceCashViewController alloc] init];
    [self.navigationController pushViewController:cash animated:YES];
    cash=nil;
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return [_sectionArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=_sectionArray.count) {
        return 40;
    }
    NSDictionary *dict = [_sectionArray objectAtIndex:indexPath.row];
    return [BalanceCell returnCellHeight:dict];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BalanceCell *cell = (BalanceCell*)[tableView  dequeueReusableCellWithIdentifier:@"BalanceCell"];
    if(cell == nil)
    {
        cell = [[BalanceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BalanceCell"];
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    if (indexPath.row>=_sectionArray.count) {
        return cell;
    }
    NSDictionary *dict = [_sectionArray objectAtIndex:indexPath.row];
    [cell showInfo:dict key:@"BalanceCell" indexPath:indexPath];
    return cell;
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row>=_sectionArray.count) {
        return;
    }
}

//====================================================
//
//====================================================
-(void)getShopBalanceList
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:[NSString stringWithFormat:@"%d",_currentPage] forKey:@"from"];
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    [OrderApi getShopBalanceList:dict success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    //    [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
     //   [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject
{
  //  [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =  [resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (self.currentPage ==0) {
                self.tbView.tableFooterView =nil;
                [self.tbView setShowsInfiniteScrolling:YES];
                [self.sectionArray removeAllObjects];
            }
            for (NSDictionary *dict in data) {
                [self.sectionArray addObject:dict];
            }
        }
       
        id userinfo =[resultObject objectForKey:@"user"];
        if (userinfo && [userinfo isKindOfClass:[NSDictionary class]]) {
            _userinfo = [NSMutableDictionary dictionaryWithDictionary:userinfo];
            NSString *user_balance =[[NSString stringWithFormat:@"%@",[_userinfo objectForKey:@"user_balance"]] replaceNullString];
            if (user_balance.length>0) {
                NSMutableDictionary *uuuserinfo = [NSMutableDictionary dictionaryWithDictionary:[ZShare sharedInstance].userInfo];
                [uuuserinfo setValue:user_balance forKey:@"user_balance"];
                [[ZShare sharedInstance] setUserInfo:uuuserinfo];
            }
            
            self.tbView.tableHeaderView = self.headerView;
            if (self.currentPage ==0)
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateuserinfo" object:nil];
            }
        }
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        if (self.isLoadFinished) {
            
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
        if(self.sectionArray.count==0)
        {
            self.tbView.tableFooterView =[self footerView];
        }
    }
    [self.tbView reloadData];
}
//=======================
//
//=======================
-(UIView *)footerView
{
    
    UIView *footerview =[[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 150)];
    footerview.backgroundColor=[UIColor clearColor];
    UIImage *iconimage =[UIImage imageNamed:@"noorder"];
    UIImageView *icon =[[UIImageView alloc] initWithFrame:CGRectMake((footerview.frame.size.width-iconimage.size.width)/2, 80, iconimage.size.width, iconimage.size.height)];
    icon.image =iconimage;
    [footerview addSubview:icon];
    
    UILabel *titleLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, icon.frame.origin.y+icon.frame.size.height+10, [UIScreen mainScreen].bounds.size.width, 20)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = UIColorFromRGB(0x999999);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT(14);
    titleLabel.text=@"余额暂时没有变动";
    [footerview addSubview:titleLabel];

    //
    titleLabel=nil;
    icon=nil;
    return footerview;
}
@end
